import csv
import os
from urllib.parse import urlparse

# 输入和输出文件路径
input_file = '/root/ws/2025/04/agiros_pkg_build_tools/archive_urls.csv'
output_file = '/root/ws/2025/04/agiros_pkg_build_tools/archive_urls_with_dst.csv'

def extract_filename(url):
    """从URL中提取文件名"""
    parsed_url = urlparse(url)
    path = parsed_url.path
    
    # 处理带有查询参数的URL（如?raw=true）
    if '?' in url and 'raw=true' in url:
        # 对于GitHub的raw链接，需要特殊处理
        path = path.split('?')[0]
        if 'blob/master/' in url:
            path = path.split('blob/master/')[-1]
    
    # 获取路径的最后一部分作为文件名
    filename = os.path.basename(path)
    return filename

# 读取CSV并添加新列
with open(input_file, 'r', encoding='utf-8') as infile, \
     open(output_file, 'w', encoding='utf-8', newline='') as outfile:
    
    reader = csv.DictReader(infile)
    fieldnames = reader.fieldnames + ['dst_url']
    
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    writer.writeheader()
    
    for row in reader:
        url = row['URL']
        filename = extract_filename(url)
        
        # 创建新的dst_url
        row['dst_url'] = f'https://gitee.com/AGIROS_Team/build_deps/raw/master/{filename}'
        writer.writerow(row)

print(f"处理完成！新文件已保存为: {output_file}")